import 'package:fluent_ui/fluent_ui.dart';
import 'dart:async';
import 'package:flutter/material.dart' show DataCell;
import 'package:flutter_web_data_table/web_data_table.dart';
import 'demodata.dart';

class TablePage extends StatefulWidget {
  const TablePage({Key? key}) : super(key: key);

  @override
  State<TablePage> createState() => _TablePageState();
}

class _TablePageState extends State<TablePage> {
  late String _sortColumnName;
  late bool _sortAscending;
  List<String>? _filterTexts;
  bool _willSearch = true;
  Timer? _timer;
  int? _latestTick;
  List<String> _selectedRowKeys = [];
  int _rowsPerPage = 10;

  @override
  void initState() {
    super.initState();
    _sortColumnName = 'browser';
    _sortAscending = false;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!_willSearch) {
        if (_latestTick != null && timer.tick > _latestTick!) {
          _willSearch = true;
        }
      }
      if (_willSearch) {
        _willSearch = false;
        _latestTick = null;
        setState(() {
          if (_filterTexts != null && _filterTexts!.isNotEmpty) {
            _filterTexts = _filterTexts;
            print('filterTexts = $_filterTexts');
          }
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _timer = null;
  }

  @override
  Widget build(BuildContext context) {
    return ScaffoldPage(
      // header: const PageHeader(title: Text("表格示例")),
      content: SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.all(8.0),
          child: WebDataTable(
            // columnSpacing: 16,
            header: const Text('表格示例'),
            actions: [
              if (_selectedRowKeys.isNotEmpty)
                SizedBox(
                  height: 50,
                  width: 100,
                  child: CommandBar(
                    overflowBehavior: CommandBarOverflowBehavior.noWrap,
                    primaryItems: [
                      CommandBarButton(
                          icon: const Icon(FluentIcons.delete),
                          label: const Text('Delete'),
                          onPressed: () {
                            print('Delete!');
                            setState(() {
                              _selectedRowKeys.clear();
                            });
                          }),
                    ],
                  ),
                ),
              Container(
                width: 300,
                child: TextBox(
                  // decoration: InputDecoration(
                  //   prefixIcon: Icon(Icons.search),
                  //   hintText: 'increment search...',
                  //   focusedBorder: const OutlineInputBorder(
                  //     borderSide: BorderSide(
                  //       color: Color(0xFFCCCCCC),
                  //     ),
                  //   ),
                  //   border: const OutlineInputBorder(
                  //     borderSide: BorderSide(
                  //       color: Color(0xFFCCCCCC),
                  //     ),
                  //   ),
                  // ),
                  onChanged: (text) {
                    _filterTexts = text.trim().split(' ');
                    _willSearch = false;
                    _latestTick = _timer?.tick;
                  },
                ),
              ),
            ],
            source: WebDataTableSource(
              sortColumnName: _sortColumnName,
              sortAscending: _sortAscending,
              filterTexts: _filterTexts,
              columns: [
                WebDataColumn(
                  name: 'id',
                  label: const Text('ID'),
                  dataCell: (value) => DataCell(Text('$value')),
                ),
                WebDataColumn(
                  name: 'renderingEngine',
                  label: const Text('Rendering engine'),
                  dataCell: (value) => DataCell(Text('$value'),
                      showEditIcon: true, onDoubleTap: () {
                    print(value);
                  }),
                ),
                WebDataColumn(
                  name: 'browser',
                  label: const Text('Browser'),
                  dataCell: (value) => DataCell(Text('$value')),
                ),
                WebDataColumn(
                  name: 'platform',
                  label: const Text('Platform(s)'),
                  dataCell: (value) => DataCell(Text('$value')),
                ),
                WebDataColumn(
                  name: 'engineVersion',
                  label: const Text('Engine version'),
                  dataCell: (value) => DataCell(Text('$value')),
                ),
                WebDataColumn(
                  name: 'cssGrade',
                  label: const Text('CSS grade'),
                  dataCell: (value) => DataCell(Text('$value')),
                  sortable: false,
                ),
                WebDataColumn(
                    name: 'dateTime',
                    label: const Text('DateTime'),
                    dataCell: (value) {
                      if (value is DateTime) {
                        final text =
                            '${value.year}/${value.month}/${value.day} ${value.hour}:${value.minute}:${value.second}';
                        return DataCell(Text(text));
                      }
                      return DataCell(Text(value.toString()));
                    },
                    filterText: (value) {
                      if (value is DateTime) {
                        return '${value.year}/${value.month}/${value.day} ${value.hour}:${value.minute}:${value.second}';
                      }
                      return value.toString();
                    }),
              ],
              rows: SampleData().data,
              selectedRowKeys: _selectedRowKeys,
              onTapRow: (rows, index) {
                print('onTapRow(): index = $index, row = ${rows[index]}');
              },
              onSelectRows: (keys) {
                print('onSelectRows(): count = ${keys.length} keys = $keys');
                setState(() {
                  _selectedRowKeys = keys;
                });
              },
              primaryKeyName: 'id',
            ),
            horizontalMargin: 100,
            onPageChanged: (offset) {
              print('onPageChanged(): offset = $offset');
            },
            onSort: (columnName, ascending) {
              print(
                  'onSort(): columnName = $columnName, ascending = $ascending');
              setState(() {
                _sortColumnName = columnName;
                _sortAscending = ascending;
              });
            },
            onRowsPerPageChanged: (rowsPerPage) {
              print('onRowsPerPageChanged(): rowsPerPage = $rowsPerPage');
              setState(() {
                if (rowsPerPage != null) {
                  _rowsPerPage = rowsPerPage;
                }
              });
            },
            rowsPerPage: _rowsPerPage,
          ),
        ),
      ),
    );
  }
}
